<?php

namespace addons\zzyy\library;

use addons\zzyy\library\Ykxbon;
use app\admin\model\zzyy\ZzyySetting;
use app\admin\model\zzyy\ZzyyThird;
use fast\Http;
use think\Log;

class Tongtongsuo
{

    public function addPassword($lockId, $user, $startDate, $endDate)
    {
//        return [
//            'blue_key_id' => '848549',
//            'blue_lock_data' => 'mockupdata',
//            'rand_key_id' => '48594',
//            'rand_key_pwd' => '7485748',
//        ];

        $config = get_addon_config('zzyy');

        $clientId = $config['tongtongsuo_client_id'];
        $clientSecret = $config['tongtongsuo_client_secret'];
        $domain = $config['tongtongsuo_domain'];

        $tongtongsuoAccesstoken = ZzyySetting::where('name', 'tongtongsuo_accesstoken')->find();
        $tongtongsuoExpirestime = ZzyySetting::where('name', 'tongtongsuo_expires_time')->find();

        $headers = ['content-type:application/x-www-form-urlencoded'];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];

        if (empty($tongtongsuoAccesstoken->value) or empty($tongtongsuoExpirestime->value)
            or time() - $tongtongsuoExpirestime->updatetime > $tongtongsuoExpirestime->value - 3600 * 24 * 2) {

            $url = $domain . '/oauth2/token';

            $postdata = [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
                'username' => $config['tongtongsuo_username'],
                'password' => md5($config['tongtongsuo_password']),
            ];

            $res = Http::post($url, http_build_query($postdata), $options);
            $res = json_decode($res, true);

            if (isset($res['access_token'])) {
                $tongtongsuoAccesstoken->value = $res['access_token'];
                $tongtongsuoExpirestime->value = $res['expires_in'];

                $tongtongsuoAccesstoken->save();
                $tongtongsuoExpirestime->save();
            } else {
                return false;
            }
        }

        //正式逻辑，下发密码和随机密码
        $postdata = [
            'clientId' => $clientId,
            'accessToken' => $tongtongsuoAccesstoken->value,
            'lockId' => $lockId,
            'receiverUsername' => $user->mobile,
            'keyName' => $lockId . '_' . $startDate,
            'startDate' => Ykxbon::parse($startDate)->getTimestampMs(),
            'endDate' => Ykxbon::parse($endDate)->getTimestampMs(),
            'createUser' => ZzyyThird::isTongTongSuoUser($user->id) ? 2 : 1,
            'date' => Ykxbon::now()->getTimestampMs()
        ];

        $blueKeyId = '';
        $randKeyId = '';
        $randKeyPwd = '';
        $lockData = '';

        $url = $domain . '/v3/key/send';

        $res = Http::post($url, http_build_query($postdata), $options);
        $res = json_decode($res, true);

        if (!isset($res['keyId'])) {
            Log::record($res, 'tongtongsuo_add_password');
            return false;
        } else {
            $blueKeyId = $res['keyId'];
        }

        $postdata = [
            'clientId' => $clientId,
            'accessToken' => $tongtongsuoAccesstoken->value,
            'lockId' => $lockId,
            'keyboardPwdType' => 3,
            'startDate' => Ykxbon::parse($startDate)->getTimestampMs(),
            'endDate' => Ykxbon::parse($endDate)->getTimestampMs(),
            'date' => Ykxbon::now()->getTimestampMs()
        ];

        $url = $domain . '/v3/keyboardPwd/get';

        $res = Http::post($url, http_build_query($postdata), $options);
        $res = json_decode($res, true);

        if (!isset($res['keyboardPwdId'])) {
            Log::record($res, 'tongtongsuo_add_password');
            return false;
        } else {
            $randKeyId = $res['keyboardPwdId'];
            $randKeyPwd = $res['keyboardPwd'];
        }

        //用户模拟登录和得到蓝牙锁的lockdata
        if (!ZzyyThird::isTongTongSuoUser($user->id)) {
            ZzyyThird::create([
                'user_id' => $user->id,
                'platform' => ZzyyThird::PLATFORM_TONGTONGSUO,
                'username' => $user->mobile,
            ]);
        }

        $third = ZzyyThird::where('user_id', $user->id)->where('platform', ZzyyThird::PLATFORM_TONGTONGSUO)->find();
        if (empty($third->access_token)
            or time() - $third->updatetime > $third->expires_in - 3600 * 24 * 2) {
            $url = $domain . '/oauth2/token';
            $postdata = [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
                'username' => $user->mobile,
                'password' => md5(substr($user->mobile, 5)),
            ];
            $res = Http::post($url, http_build_query($postdata), $options);
            $res = json_decode($res, true);

            if (isset($res['access_token'])) {
                $third->access_token = $res['access_token'];
                $third->expires_in = $res['expires_in'];

                $third->save();
            } else {
                Log::record($res, 'tongtongsuo_add_password');
                return false;
            }
        }

        //得到单把钥匙
        $url = $domain . '/v3/key/get';
        $res = Http::get($url, [
            'clientId' => $clientId,
            'accessToken' => $third->access_token,
            'lockId' => $lockId,
            'date' => Ykxbon::now()->getTimestampMs(),
        ]);
        $res = json_decode($res, true);

        if (isset($res['lockData'])) {
            $lockData = $res['lockData'];
        } else {
            Log::record($res, 'tongtongsuo_add_password');
            return false;
        }

        return [
            'blue_key_id' => $blueKeyId,
            'blue_lock_data' => $lockData,
            'rand_key_id' => $randKeyId,
            'rand_key_pwd' => $randKeyPwd,
        ];
    }



}